package org.dm.controller;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

public class HttpController {

    private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json;charset=utf-8");
    public static HttpController instance;
    private final OkHttpClient okHttpClient;

    private HttpController() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .build();
    }

    public static HttpController getInstance() {
        if (instance == null) {
            instance = new HttpController();
        }
        return instance;
    }

    public Response doGet(String url) throws Exception {
        return this.doGet(url, null);
    }

    public Response doGet(String url, HashMap<String, String> params) throws Exception {
        Logger.getGlobal().info("---GET请求---url地址：【" + url + "】");
        HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
        if (params != null) {
            for (Map.Entry<String, String> param : params.entrySet()) {
                httpBuilder.addQueryParameter(param.getKey(), param.getValue());
            }
        }
        Request request = new Request.Builder()
                .url(httpBuilder.build())
                .get().build();
        Call call = okHttpClient.newCall(request);
        return call.execute();
    }

    public Response doPost(String url, HashMap<String, String> headers, JSONObject jsonParams) throws Exception {
        Logger.getGlobal().info("---POST请求---url地址：【" + url + "】");

        RequestBody requestBody = RequestBody.create(jsonParams.toString(), MEDIA_TYPE_JSON);
        Request request = new Request.Builder()
                .url(url)
                .headers(Headers.of(headers))
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        return call.execute();
    }

    public JSONObject getJsonBody(Response response) throws IOException {
        return JSONObject.parseObject(response.body().string());
    }

    public HashMap<String, Object> getHashMapBody(JSONObject jsonObject) {
        HashMap<String, Object> hashMap = new HashMap<>();
        for (String key : jsonObject.keySet()) {
            String value = jsonObject.getString(key);
            if (value.startsWith("{") && value.endsWith("}")) {
                hashMap.put(key, getHashMapBody(jsonObject.getJSONObject(key)));
            } else if (value.startsWith("[") && value.endsWith("]")) {
                JSONArray array = jsonObject.getJSONArray(key);
                hashMap.put(key, parseJsonArray(array));
            } else {
                hashMap.put(key, value);
            }
        }
        return hashMap;
    }

    private List<Object> parseJsonArray(JSONArray array) {
        List<Object> list = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            String arrayValue = array.getString(i);
            if (arrayValue.startsWith("{") && arrayValue.endsWith("}")) {
                list.add(getHashMapBody(array.getJSONObject(i)));
            } else if (arrayValue.startsWith("[") && arrayValue.endsWith("]")) {
                this.parseJsonArray(array.getJSONArray(i));
            } else {
                list.add(arrayValue);
            }
        }
        return list;
    }

}
